 import axios from "axios";
 const baseUrl = '/api'
 import qsString from 'querystring'

 // 请求拦截
 axios.interceptors.request.use(req => {

    if(req.url != '/api/userlogin'){
        //不是登录就要添加请求头
        req.headers.authorization= sessionStorage.getItem('user')?JSON.parse(sessionStorage.getItem('user')).token:null
      }
     return req
 })
 // 响应拦截
 axios.interceptors.response.use(res => {
     return res.data
 })


 // 封装get请求
 export const get = (url, params = {}) => {
     return new Promise((resolve, request) => {
         axios.get(baseUrl+url, {
                 params
             })
             .then(res => {
                 resolve(res)
             })
             .catch(err => {
                 request(err)
             })
     })
 }

 //  封装post请求
 export const post = (url, params = {}, isfile = false) => {
     let data = {}
     if (isfile) {
         data = new FormData;
         for (let i in params) {
             data.append(i, params[i])
         }
     } else {
        //  data = qsString.stringify(params)
         data = qsString.stringify(params)
     }

     return new Promise((resolve, request) => {
         axios.post(baseUrl+url, data)
             .then(res => {
                 resolve(res)
             })
             .catch(err => {
                 request(err)
             })
     })

 }